<?php

namespace App\Http\Controllers\Home;

use App\Http\Requests\DangercheckRequest;
use App\Model\Checkaccord;
use App\Model\Checkentry;
use App\Model\Comcheckdanger;
use App\Model\Comcheckdangerdetail;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Model\Company;
use App\Model\Comcheck;
use App\Model\Comcheckdetail;
use App\User;
use App\Model\Checknegative;
use App\Services\ImageClass;
use Illuminate\Support\Facades\DB;

class DangerController extends Controller
{
    protected $comCheckDangerObj;
    protected $companyClass;

    public function __construct(Comcheckdanger $comcheckdanger, Company $company)
    {
        $this->comCheckDangerObj = $comcheckdanger;
        $this->companyClass = $company;
    }

    /*自查隐患整改页面*/
    public function dangercheck($id)
    {
        $company = Company::find($id);
        if(empty($company)) {
            \Session::flash('error', '公司不存在!');
            return back();
        }
        if($company['type']!=2) {
            \Session::flash('error', '公司信息错误!');
            return back();
        }
        if($company['schedule']==1) {
            \Session::flash('error', '公司还没进行初查!');
            return back();
        }
        /*获取初查信息*/
        $comcheck_where = array();
        $comcheck_where[] = array('companyId', $company['id']);
        $comcheck = Comcheck::where($comcheck_where)->first();
        if(empty($comcheck)) {
            \Session::flash('error', '请选择初查!');
            return back();
        }
        /*获取自查信息*/
        $check_danger_where = array();
        $check_danger_where[] = array('companyId', $company['id']);
        $com_check_danger = Comcheckdanger::where($check_danger_where)->orderBy('checkTime','DESC')->first();
        /*获取初步检查人员*/
        $checkUser = User::where('id', $comcheck->userId)->first();
        $comcheck['checkUser'] = $checkUser;
        /*隐患列表(初查部分查完也可以查，检查自查和初查,根据初查和自查的检查时间确定读取哪些选项)*/
        $check_list_from = 'check';
        if(!empty($com_check_danger)) {
            if($comcheck['updated']<$com_check_danger['checkTime']) {/*选择自查结果进行自查*/
                $check_list_from = 'checkDanger';
            }
        }
        if($check_list_from=='check') {/*从初查表中读取信息*/
            $where = array();
            $where[] = array('checkId', $comcheck->id);
            $where[] = array('status', 2);
            $dangers = Comcheckdetail::where($where)->get();
            $teble = 'comcheck';
        } else {/*从自查表中读取信息*/
            $where = array();
            $where[] = array('checkId', $com_check_danger->id);
//            $where[] = array('status', '<>', 3);
            $dangers = Comcheckdangerdetail::where($where)->get();
//            $where = array();
//            $dangers = Comcheckdangerdetail::where('checkId','=',$com_check_danger->id)->where('status', '!=', 3)->get();
            $teble = 'comdanger';

        }
        if(empty($dangers)) {
            \Session::flash('error', '没有隐患存在!');
            return back();
        } else {
            /*图片转数组*/
            foreach($dangers as $k=>$val) {
                $dangers[$k]->picturesArr = array();
                if(!empty($val->pictures)) {
                    $dangers[$k]->picturesArr = explode(',', trim($val->pictures,','));
                }
            }
            /*获取违规项*/
            $negativesObj = new Checknegative();
            $negativess = $negativesObj->getChecknegativeByCheckId($comcheck->id);
            $negativess = json_decode(json_encode($negativess),true);

            foreach($dangers as $k=>$v) {
                if(!empty($v->entryId)){
                    $dangers[$k]->negatives = '';
                    $dangers[$k]->entry = Checkentry::find($v->entryId)->entry;
                    $checkaccord = Checkaccord::where('entryId','=',$v->entryId)->first();
                    if (!empty($checkaccord->title)){
                        $dangers[$k]->accord = $checkaccord->title.$checkaccord->content;
                    }else{
                        $dangers[$k]->accord = '';
                    }

                    foreach($negativess as $key=>$val) {
                        if($v->entryId == $val['entryId']) {
                            $dangers[$k]->negatives .= $val['content'].'/';
                        }
                    }
                }
//                dd($v->entryId);

            }
//            $dangers = json_decode(json_encode($dangers),true);
//            dd($dangers);
//            $dangers = json_decode(json_encode($dangers),true);
//            dd($dangers);
            /*获取企业自查信息*/
        }
        $dangersjson = json_decode(json_encode($dangers), true);
//        if(empty($dangersjson)) {
//            \Session::flash('error', '隐患已整改!');
//            return back();
//        }
        return view('danger.dangercheck', array(
                'company' => $company,
                'comcheck' => $comcheck,
                'dangers' => $dangers,
                'come_from' => $check_list_from
            )
        );

    }
    /*自查信息保存*/
    public function checkDangerSave(DangercheckRequest $request)
    {
        $data = $request->input();
//        dd($data);
        $hideDanger = $data['hideDanger'];/*隐患*/
        $companyId = $data['companyId'];
        $checkData = array();
        $checkDetailData = array();
        $company = $this->companyClass->find($companyId);
        if(empty($company)) {
            \Session::flash('error', '公司不存在!');
            return back();
        }
        if($company['type']!=2) {
            \Session::flash('error', '公司信息错误!');
            return back();
        }
        if($company['schedule']==1) {
            \Session::flash('error', '公司还没进行初查!');
            return back();
        }
        /*验证是否已经初查*/
        $check_where = array();
        $check_where[] = array('companyId', $companyId);
        $com_check = Comcheck::where($check_where)->first();
        if(empty($com_check)) {
            \Session::flash('error', '请先选择初查!');
            return back();
        }

        $checkData['companyId'] = $companyId;
        $user = Auth::user();
        $checkData['userId'] = $user['id'];
        $checkData['checkId'] = $com_check['id'];
        $checkData['checkTime'] = time();
        $come_from = $data['come_from'];
        if($come_from=='check') {
            $checkData['from'] = 1;
        } else if($come_from=='checkDanger') {
            $checkData['from'] = 2;
        }
        /*签名转化成图片*/
        $imageObj = new ImageClass();
        $checkData['companySign'] = $imageObj->base64toimg($data['companySign']);
        /*使用事务插入*/
        DB::beginTransaction();
        try{
            $checkRes = Comcheckdanger::create($checkData);
            if($checkRes !== false) {
                /*插入复查选项*/
//                dd($hideDanger);
                foreach($hideDanger as $k=>$v) {
                    $tmpArr = array();
                    $tmpArr['checkId'] = $checkRes['id'];
                    if(!empty($v['entryId'])) {
                        $tmpArr['entryId'] = $v['entryId'];
                    } else {
                        $tmpArr['entryId'] = 0;
                    }
                    if(!empty($v['detailId'])) {
                        $tmpArr['detailId'] = $v['detailId'];
                    } else {
                        $tmpArr['detailId'] = 0;
                    }
                    $tmpArr['status'] = $v['status'];
                    $tmpArr['content'] = $v['content'];

                    if ($v['status'] == 3){
                        $tmpArr['remark'] = $v['remark'];
                        $pictures = "";
                        $pictures = $v['pictures'];
                        if(!empty($pictures)) {
                            $tmpArr['pictures'] = trim($pictures,",");
                        } else {
                            $tmpArr['pictures'] = "";
                        }
                    }else{
                        $tmpArr['remark'] = '';
                        $tmpArr['pictures'] = '';
                    }



                    $tmpArr['userId'] = $user['id'];
                    $tmpArr['groupId'] = $v['groupId'];
                    $tmpArr['checkDetailId'] = $v['checkDetailId'];
                    $checkDetailData[] = $tmpArr;
                }
                $comCheckDangerDetailObj = new Comcheckdangerdetail();
                $checkDetailRes = $comCheckDangerDetailObj->addAll($checkDetailData);

                /*修改公司表*/
//                if($come_from=='check') {
//                    $companyData = array();
//                    $companyData['schedule'] = 3;
//                    $company->update($companyData);
//                }
            }
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            \Session::flash('error', $e->getMessage());
            return back();
        }
        return redirect('choose');
    }
}
